package org.luxor.commons.excel.component.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.extension.service.IService;
import org.luxor.commons.core.validator.ValidatorUtils;
import org.luxor.commons.excel.exception.ReadExcelException;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Mr.Yan
 **/
public class ExcelReadListener<T> extends AnalysisEventListener<T> {
    /**
     * 每隔3000条存储数据库，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 3000;

    /**
     * 业务数据
     */
    private List<T> datas = new ArrayList<>();

    private IService<T> service;

    public ExcelReadListener(IService<T> service) {
        this.service = service;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        String message = "无法读取Excel(" + context.readSheetHolder().getSheetName() + "工作表,第"
                + context.readRowHolder().getRowIndex() + "行)数据";
        throw new ReadExcelException(message, exception);
    }

    /**
     * 每一条数据的解析都会调用此方法
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(T data, AnalysisContext context) {
        if (data == null) {
            return;
        }

        // 校验数据
        ValidatorUtils.validateEntity(data);

        datas.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止几万条数据在内存，容易OOM
        if (datas.size() >= BATCH_COUNT) {
            batchSave();
            // 存储完成清理 list
            datas.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        batchSave();
    }

    /**
     * 存入数据库
     */
    private void batchSave() {
        if (service != null) {
            this.service.saveOrUpdateBatch(datas);
        }
    }
}
